<script setup lang="ts">
import { ref, reactive } from "vue";
import {
  queryGoodsList,
  addGoods,
  updateGoods,
  deleteShop,
  onshelf,
  unshelf
} from "@/api/shop";
import { uploadUrl } from "@/api/global";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";
import { request } from "http";
defineOptions({
  name: "shop"
});
const currentPage = ref(1);
const pageSize = ref(10); // 添加这行

const pageTotal = ref(0);
let tableData = ref([]);
const type = ref("");
let previewUrl = ref("");
let previewServiceUrl = ref("");
const statusList = [
  { label: "已上架", value: "NORMAL" },
  { label: "已下架", value: "UNSHELF" }
];
// 修改查询参数
const queryParams = reactive({
  goodsName: "",
  status: "",
  pageNo: 1,
  pageSize: 10
});
//分类列表
// initCategoryList();
//初始化列表
queryListTableData();
// 修改查询列表函数
function queryListTableData(params?) {
  const _params = {
    pageNo: 1,
    pageSize: 10,
    total: 0,
    ...params
  };
  if (queryParams.goodsName) {
    _params.goodsName = queryParams.goodsName;
  }
  if (queryParams.status) {
    _params.status = queryParams.status;
  }
  queryGoodsList({ ..._params }).then((res: any) => {
    console.log(res, "res");
    tableData.value = res.data.data;
    pageTotal.value = res.data.total;
  });
}
//筛选
const ruleFormRef = ref<FormInstance>();

// 修改重置函数
const onReset = () => {
  queryParams.goodsName = "";
  queryParams.status = "";
  queryParams.pageNo = 1;
  pageTotal.value = 0;
  currentPage.value = 1;
  queryListTableData();
};

// 修改表单数据
const ruleForm = reactive({
  goodsName: "",
  price: "",
  points: "",
  mainImage: "",
  description: "",
  stockCount: "",
  saleCount: ""
});

// 修改验证规则
const rules = reactive<FormRules<typeof ruleForm>>({
  goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  points: [{ required: true, message: "请输入积分数量", trigger: "blur" }],
  stockCount: [{ required: true, message: "请输入库存数量", trigger: "blur" }],
  saleCount: [{ required: true, message: "请输入销量", trigger: "blur" }],
  mainImage: [{ required: true, message: "请上传主图", trigger: "blur" }]
});

// 修改详情数据
const detailInfo = reactive({
  serviceName: "",
  price: "",
  serviceDuration: "",
  horizontalImage: "",
  vipPrice: "",
  description: "",
  mainImage: ""
});
//添加
const addRoleDialogVisible = ref(false);
// 在其他 ref 声明附近添加
const categoryList = ref([]);

// 在 initStoreList 函数后添加
// function initCategoryList() {
//   queryCategoryList().then((res: any) => {
//     categoryList.value = res.data;
//   });
// }

// 在 handleAddRole 函数中添加技能列表初始化
function handleAddRole(mark) {
  addRoleDialogVisible.value = true;
  type.value = mark;
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = key === "skills" ? [] : "";
  });
}
function addRoleInfo() {
  addGoods({
    goodsName: ruleForm.goodsName,
    price: ruleForm.price,
    points: ruleForm.points,
    mainImage: ruleForm.mainImage,
    description: ruleForm.description,
    stockCount: ruleForm.stockCount,
    saleCount: ruleForm.saleCount
  })
    .then((res: any) => {
      console.log(res);
      ElMessage({
        type: "success",
        message: res.message
      });
      addRoleDialogVisible.value = false;
      queryListTableData();
    })
    .catch((err: any) => {
      console.log(err);
      ElMessage({
        type: "error",
        message: err.message
      });
    });
}
//编辑
const editId = ref("");
const handleEditRole = async (row, mark) => {
  console.log(row, "data");

  type.value = mark;
  editId.value = row.id;
  addRoleDialogVisible.value = true;
  ruleForm.price = row.price;
  ruleForm.points = row.points;
  ruleForm.stockCount = row.stockCount;
  ruleForm.saleCount = row.saleCount;
  ruleForm.goodsName = row.goodsName;
  ruleForm.description = row.description;
  ruleForm.mainImage = row.mainImage;
  console.log(ruleForm, "ruleForm");
};
function editRoleInfo() {
  console.log(ruleForm, "ruleForm");
  // 处理图片URL
  const mainImageUrl = ruleForm.mainImage.includes(
    "https://www.itbenma.com/budcare"
  )
    ? ruleForm.mainImage.replace("https://www.itbenma.com/budcare", "")
    : ruleForm.mainImage;
  updateGoods({
    goodsName: ruleForm.goodsName,
    points: ruleForm.points,
    stockCount: ruleForm.stockCount,
    saleCount: ruleForm.saleCount,
    price: ruleForm.price,
    mainImage: mainImageUrl,
    description: ruleForm.description,
    id: editId.value
  }).then((res: any) => {
    console.log(res);
    addRoleDialogVisible.value = false;
    ElMessage({
      type: "success",
      message: res.message
    });
    queryListTableData();
  });
}
//上下架
const handleStatus = async row => {
  if (row.status == "UNSHELF") {
    ElMessageBox.confirm("确认是否上架?", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      onshelf({ id: row.id }).then((res: any) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: res.message
          });
          queryListTableData();
        } else {
          ElMessage({
            type: "error",
            message: res.message
          });
        }
      });
    });
  }
  if (row.status == "NORMAL") {
    ElMessageBox.confirm("确认是否下架?", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      unshelf({ id: row.id }).then((res: any) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: res.message
          });
          queryListTableData();
        } else {
          ElMessage({
            type: "error",
            message: res.message
          });
        }
      });
    });
  }
};

//提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      console.log("submit!");
      if (type.value == "add") {
        addRoleInfo();
      } else if (type.value == "edit") {
        editRoleInfo();
      }
    } else {
      console.log("error submit!");
    }
  });
};
//删除用户
const handleDeteleRole = async (record: Recordable) => {
  // const type = await VxeUI.modal.confirm("您确定要删除吗？");
  ElMessageBox.confirm("确认是否删除?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteShop({ id: record.id })
        .then((res: any) => {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          queryListTableData();
        })
        .catch((err: any) => {
          console.log(err);
          ElMessage({
            type: "error",
            message: err.message
          });
        });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "删除失败"
      // });
    });
};
//重置添加用户
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per pserviceName`);
  queryListTableData({ ...queryParams, pageNo: val });
};

const handleCurrentChange = (val: number) => {
  console.log(`current pserviceName: ${val}`);
  queryListTableData({ ...queryParams, pageNo: val });
};
function handleClose() {
  console.log("关闭");
  addRoleDialogVisible.value = false;
}
// 头像上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    console.log(response, "response");
    // 使用完整的URL路径
    ruleForm.horizontalImage = response.data.dataUrl;
    // ruleForm.avatar = import.meta.env.VITE_API_URL + response.data;
    // 或者使用相对路径（取决于你的项目配置）
    uploadFile.url = response.data.previewUrl;
    previewUrl.value = uploadFile.url;
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 横向图片上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传横向图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传横向图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
// 主图上传成功的回调
const handleServiceSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    console.log(response, "response");
    // 使用完整的URL路径
    ruleForm.mainImage = response.data.dataUrl;
    // ruleForm.avatar = import.meta.env.VITE_API_URL + response.data;
    // 或者使用相对路径（取决于你的项目配置）
    uploadFile.url = response.data.previewUrl;
    previewServiceUrl.value = uploadFile.url;
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 主图图片上传前的校验
const beforeServiceUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传主图图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传主图图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
</script>
<template>
  <div class="statement">
    <div class="search">
      <div class="c-input">
        <el-input
          v-model="queryParams.goodsName"
          clearable
          placeholder="请输入商品名称"
        />
      </div>
      <div class="c-input">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="search-btn">
        <el-button type="primary" size="large" @click="queryListTableData"
          >查询</el-button
        >
        <el-button size="large" @click="onReset">重置</el-button>
      </div>
    </div>
    <div class="add">
      <el-button type="primary" size="large" @click="handleAddRole('add')"
        ><el-icon> <Plus /> </el-icon>添加商品</el-button
      >
    </div>
    <div class="c-pserviceName__bg">
      <el-table :data="tableData">
        <el-table-column prop="id" label="商品ID" width="200" />
        <el-table-column prop="goodsName" label="商品名称" width="200" />
        <el-table-column
          prop="price"
          label="商品原价格（单位：元）"
          min-width="120"
        />
        <el-table-column prop="points" label="兑换积分" />
        <el-table-column prop="saleCount" label="已售数量" />
        <el-table-column label="主图地址">
          <template #default="scope">
            <el-image
              :src="scope.row.mainImage"
              fit="cover"
              style="width: 50px; height: 50px; cursor: pointer"
              :preview-src-list="[scope.row.mainImage]"
              :initial-index="0"
              preview-teleported
              :hide-on-click-modal="true"
            />
          </template>
        </el-table-column>
        <el-table-column prop="statusName" label="状态" />
        <el-table-column prop="stockCount" label="库存数量" />
        <el-table-column
          prop="createTimeStr"
          label="创建时间"
          min-width="150"
        />
        <el-table-column
          prop="unshelfTimeStr"
          label="下架时间"
          min-width="150"
        />
        <el-table-column prop="description" label="描述" min-width="150">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="`<span style='width:200px;display:inline-block;white-space:normal;'>${scope.row.description}</span>`"
              raw-content
            >
              <div class="description-cell">{{ scope.row.description }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          #default="{ row }"
          label="操作"
          width="220"
          fixed="right"
        >
          <span
            v-if="row.status == 'UNSHELF'"
            class="c-text-primary"
            @click="handleStatus(row)"
            >上架</span
          >
          <span
            v-if="row.status == 'NORMAL'"
            class="c-text-primary"
            @click="handleStatus(row)"
            >下架</span
          >
          <span class="c-text-primary" @click="handleEditRole(row, 'edit')"
            >修改</span
          >
          <span class="c-text-primary" @click="handleDeteleRole(row)">
            删除
          </span>
        </el-table-column>
      </el-table>
      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pageTotal"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :pserviceName-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="addRoleDialogVisible"
      :title="type == 'detail' ? '查看详情' : '添加/编辑商品'"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        v-if="type == 'detail'"
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称">{{
          detailInfo.serviceName
        }}</el-form-item>
        <el-form-item label="项目价格">{{ detailInfo.price }}</el-form-item>
        <el-form-item label="项目名称">{{
          detailInfo.serviceName
        }}</el-form-item>
        <el-form-item label="服务时长">{{
          detailInfo.serviceDuration
        }}</el-form-item>
        <el-form-item label="头像">
          <img
            v-if="detailInfo.avatarUrl"
            :src="detailInfo.avatarUrl"
            class="avatar"
          />
        </el-form-item>
        <el-form-item label="所属门店">{{ detailInfo.storeName }}</el-form-item>
        <el-form-item label="入职时间">{{ detailInfo.enterTime }}</el-form-item>
        <el-form-item label="状态">{{ detailInfo.statusName }}</el-form-item>
        <el-form-item label="专业技能">
          <span v-for="(item, index) in detailInfo.skills" :key="index"
            >{{ item.skillName }}
            <i v-if="index != detailInfo.skills.length - 1">,</i></span
          >
        </el-form-item>
        <el-form-item label="生日">{{ detailInfo.birthdayStr }}</el-form-item>
        <el-form-item label="介绍">{{ detailInfo.description }}</el-form-item>
      </el-form>

      <el-form
        v-else
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称" prop="goodsName">
          <el-input
            v-model="ruleForm.goodsName"
            type="text"
            autocomplete="off"
            placeholder="请输入商品名称"
          />
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input
            v-model="ruleForm.price"
            type="price"
            autocomplete="off"
            placeholder="请输入商品价格"
          />
        </el-form-item>
        <el-form-item label="已售数量" prop="saleCount">
          <el-input
            v-model="ruleForm.saleCount"
            type="number"
            autocomplete="off"
            min="0"
            placeholder="请输入已售数量"
          />
        </el-form-item>
        <el-form-item label="库存数量" prop="stockCount">
          <el-input
            v-model="ruleForm.stockCount"
            type="number"
            min="0"
            autocomplete="off"
            placeholder="请输入库存数量"
          />
        </el-form-item>
        <el-form-item label="积分数量" prop="points">
          <el-input
            v-model="ruleForm.points"
            type="text"
            autocomplete="off"
            placeholder="请输入积分数量"
          />
        </el-form-item>
        <el-form-item label="主图链接" prop="mainImage">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="uploadUrl"
            :data="{ type: 'service' }"
            :before-upload="beforeServiceUpload"
            :on-success="handleServiceSuccess"
          >
            <img
              v-if="ruleForm.mainImage && !previewServiceUrl"
              :src="ruleForm.mainImage"
              class="avatar"
            />
            <img
              v-else-if="previewServiceUrl"
              :src="previewServiceUrl"
              class="avatar"
            />
            <div v-else>
              <el-icon class="avatar-uploader-icon">
                <Plus />
              </el-icon>
              <div class="upload-text">请上传主图图片</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="textarea"
            autocomplete="off"
            placeholder="请输入描述信息"
          />
        </el-form-item>
        <el-form-item
          v-if="type != 'detail'"
          label="  "
          style="margin-top: 30px"
        >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.statement {
  height: 100%;
  overflow: hidden;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.search {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 8px;
  display: flex;
  // align-items: center;
  flex-wrap: wrap;
  .c-input {
    width: 240px !important;
    margin-bottom: 16px;
    margin-right: 16px;
    --el-border-radius-base: 8px;
    --el-input-focus-border-color: var(--main-color) !important;
    --el-component-size: 40px;
  }

  .search-btn {
    padding-left: 15px;
    .c-btn {
      height: 38px;
      border-radius: 8px;
      box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
    }
  }
}

.c-pserviceName__bg {
  width: 100%;
  height: 100%;
  margin-top: 25px;
  padding-bottom: 24px;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.c-text-primary {
  font-size: 14px;
  color: #1c9fff;
  white-space: nowrap;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.pagination-block {
  padding-top: 20px;
  padding-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.c-dot-success,
.c-dot-info {
  width: 6px;
  height: 6px;
  margin-right: 6px;
  display: inline-block;
  border-radius: 50%;
  flex-shrink: 0;
  background-color: #43bf0a;
}

.c-dot-info {
  background-color: #bfbfbf;
}

.system-icon-content {
  min-height: 500px;
}

.flex-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #262626;
}

.back {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #1c9fff;

  .back-text {
    display: flex;
    align-items: center;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .title {
    color: #8c8c8c;
    font-size: 16px;
  }
}
.c-drawer-form {
  .c-info__title {
    margin-top: 20px;
    margin-bottom: 20px;
    color: #262626;
    font-size: 16px;
  }
  .el-form-item {
    margin-left: 60px;
    margin-bottonm: 10px;
  }
}
.el-drawer__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdcdc;
  margin-bottom: 0;
}
.upload-text {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

// ... 上传图片 ...

.avatar-uploader,
.qrcode-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.required-label::before {
  content: "*";
  color: var(--el-color-danger);
  margin-right: 4px;
}

// ... 其他样式 ...
.qrcode-uploader-icon,
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  text-align: center;
  line-height: 100px;
}

.qrcode,
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.description-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
  cursor: pointer;
}
</style>
